<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>组态可视化系统</title>
    
    <!-- 全局错误处理 - 静默浏览器扩展错误 -->
    <script>
        // 捕获并静默浏览器扩展产生的错误
        window.addEventListener('error', function(event) {
            // 检查是否是扩展相关错误
            if (event.message && (
                event.message.includes('message port closed') ||
                event.message.includes('message channel closed') ||
                event.message.includes('Extension context invalidated')
            )) {
                console.warn('🔇 已忽略浏览器扩展错误:', event.message);
                event.preventDefault(); // 阻止错误显示
                return true;
            }
        });
        
        // 捕获未处理的 Promise 拒绝（扩展相关）
        window.addEventListener('unhandledrejection', function(event) {
            if (event.reason && event.reason.message && (
                event.reason.message.includes('message port closed') ||
                event.reason.message.includes('message channel closed') ||
                event.reason.message.includes('Extension context invalidated')
            )) {
                console.warn('🔇 已忽略浏览器扩展Promise错误:', event.reason.message);
                event.preventDefault(); // 阻止错误显示
            }
        });
        
        // 静默 Chrome runtime 错误
        if (window.chrome && chrome.runtime) {
            const originalRuntime = chrome.runtime;
            try {
                Object.defineProperty(chrome, 'runtime', {
                    get: function() {
                        return {
                            ...originalRuntime,
                            lastError: undefined
                        };
                    }
                });
            } catch (e) {
                // 如果无法覆盖，忽略错误
            }
        }
    </script>
    
    <!-- 认证检查脚本 - 必须最先执行 -->
    <script src="./scripts/auth/auth.js"></script>
    
    <!-- 样式文件 -->
    <link rel="stylesheet" href="./styles/main.css">
    <link rel="stylesheet" href="./styles/controls.css">
    <link rel="stylesheet" href="./styles/editor.css">
    <link rel="stylesheet" href="./styles/material-editor.css">
    <link rel="stylesheet" href="./styles/material-editor-textures.css">
    <link rel="stylesheet" href="./styles/material-editor-panel.css">
    <link rel="stylesheet" href="./styles/texture-library.css">
    <link rel="stylesheet" href="./styles/model-stats.css">
    <link rel="stylesheet" href="./styles/inspector.css">
    <link rel="stylesheet" href="./styles/loading.css">
    <link rel="stylesheet" href="./styles/two-stage-upload.css">
    
    <!-- 添加importmap解决裸模块标识符解析问题 - 必须在所有模块脚本之前 -->
    <script type="importmap">
        {
            "imports": {
                "three": "./lib/three/build/three.module.js",
                "three/addons/": "./lib/three/examples/jsm/"
            }
        }
    </script>
    
    <!-- 配置管理脚本 -->
    <script type="module">
        // 导入配置管理器
        import configManager from './scripts/core/config.js';
        
        // 应用初始化函数
        async function initializeApp() {
            try {
                // 等待配置加载
                await configManager.loadConfig();
                
                // 应用配置
                configManager.applyConfig();
                
            } catch (error) {
                console.error('❌ 应用初始化失败:', error);
            }
        }
        
        // 立即执行初始化
        initializeApp();
    </script>
    
    <!-- 初始化脚本 -->
    <script src="./scripts/core/init.js"></script>
    
    <!-- 环境面板布局压缩样式覆盖 -->
    <style>
        /* 压缩环境面板间隔，使参数完整显示 */
        .environment-container {
            gap: 6px !important;
        }
        
        .env-section {
            margin-bottom: 0 !important;
        }
        
        .env-section-header {
            padding: 8px 10px !important;
        }
        
        .env-section-body {
            gap: 6px !important;
            padding: 8px !important;
        }
        
        .env-item {
            gap: 4px !important;
        }
        
        .env-item label,
        .env-property-label {
            font-size: 10px !important;
            margin-bottom: 3px !important;
        }
        
        .env-property-row {
            margin-bottom: 8px !important;
        }
        
        .env-model-info {
            gap: 4px !important;
            padding: 5px 6px !important;
            min-height: 28px !important;
        }
        
        .env-model-name {
            font-size: 10px !important;
        }
        
        .env-transform-row {
            gap: 3px !important;
        }
        
        /* XYZ输入行 - 最关键的压缩 */
        .env-xyz-row {
            gap: 2px !important;
        }
        
        .env-xyz-input {
            flex: 1 !important;
            max-width: 80px !important; /* 限制最大宽度，压缩一半 */
            gap: 1px !important;
            padding: 1px 2px !important;
            border-radius: 2px !important;
        }
        
        .env-xyz-input input {
            width: 100% !important;
            font-size: 12px !important; /* 字体缩小到12px (16*0.75) */
            padding: 4px 2px !important;
            line-height: 1.4 !important;
            text-align: center !important;
            font-weight: 500 !important; /* 稍微加粗，更清晰 */
        }
        
        .env-axis-label {
            font-size: 9px !important; /* 轴标签缩小到9px (12*0.75) */
            min-width: 10px !important;
            flex-shrink: 0 !important;
            font-weight: 600 !important;
        }
        
        /* 缩放控制 */
        .env-scale-control {
            gap: 4px !important;
        }
        
        .env-scale-control input[type="number"] {
            width: 45px !important;
            padding: 2px 4px !important;
            font-size: 10px !important;
        }
        
        .env-input-small {
            padding: 4px 6px !important;
            font-size: 10px !important;
        }
        
        .env-btn {
            padding: 5px 10px !important;
            font-size: 10px !important;
        }
        
        .env-btn-small {
            padding: 3px 6px !important;
            font-size: 9px !important;
        }
        
        /* 下拉选择框 */
        .env-select {
            padding: 4px 6px !important;
            font-size: 10px !important;
        }
        
        /* 颜色选择器 */
        .env-color {
            width: 50px !important;
            height: 26px !important;
        }
        
        /* 滑块容器 */
        .env-slider-container {
            display: flex !important;
            align-items: center !important;
            gap: 4px !important;
        }
        
        .env-slider {
            flex: 1 !important;
        }
        
        /* 滑块值显示 */
        .env-value {
            font-size: 10px !important;
            min-width: 30px !important;
        }
        
        /* 复选框 */
        .env-checkbox {
            width: 14px !important;
            height: 14px !important;
        }
        
        /* 图标缩小 */
        .env-icon {
            font-size: 14px !important;
        }
        
        .env-title {
            font-size: 11px !important;
        }
        
        /* 子分组标题样式 */
        .env-subsection-title {
            font-size: 10px !important;
            font-weight: bold;
            color: #4a9eff;
            margin-top: 12px;
            margin-bottom: 6px;
            padding: 4px 0;
            border-bottom: 1px solid rgba(74, 158, 255, 0.3);
        }
        
        /* 数字输入框样式 */
        .env-number {
            width: 80px;
            padding: 4px 6px;
            border: 1px solid rgba(255, 255, 255, 0.2);
            background: rgba(0, 0, 0, 0.3);
            color: #ffffff;
            border-radius: 3px;
            font-size: 10px;
        }
        
        .env-number:focus {
            outline: none;
            border-color: #4a9eff;
            background: rgba(0, 0, 0, 0.5);
        }
        
        /* 环境光和天空盒的标签与输入框横向布局 */
        .env-section-body .env-item {
            display: flex !important;
            flex-direction: row !important;
            align-items: center !important;
            justify-content: space-between !important;
        }
        
        .env-section-body .env-item label {
            margin-bottom: 0 !important;
            flex-shrink: 0 !important;
        }
        
    </style>
</head>
<body>
    <!-- 全局消息提示容器 -->
    <div id="global-message-container" class="global-message-container"></div>
    
    <!-- 项目加载界面（双阶段：项目+场景）- 默认显示 -->
    <div id="project-loading-overlay" class="loading-overlay" style="display: flex;">
        <div class="loading-container">
            <!-- 加载动画 -->
            <div class="loading-spinner"></div>
            
            <!-- 标题 -->
            <div class="loading-title">加载项目中</div>
            <div class="loading-subtitle">正在准备您的工作环境...</div>
            
            <!-- 阶段1: 加载项目 -->
            <div class="loading-stage">
                <div class="stage-header">
                    <span class="stage-icon" id="project-stage-icon">⏳</span>
                    <span class="stage-title">阶段 1: 加载项目</span>
                    <span class="stage-percent" id="project-stage-percent">0%</span>
                </div>
                <div class="stage-progress-container">
                    <div id="project-stage-bar" class="stage-progress-bar"></div>
                </div>
                <div class="stage-detail" id="project-stage-detail">等待开始...</div>
            </div>
            
            <!-- 阶段2: 加载场景 -->
            <div class="loading-stage">
                <div class="stage-header">
                    <span class="stage-icon" id="scene-stage-icon">⏳</span>
                    <span class="stage-title">阶段 2: 加载场景</span>
                    <span class="stage-percent" id="scene-stage-percent">0%</span>
                </div>
                <div class="stage-progress-container">
                    <div id="scene-stage-bar" class="stage-progress-bar"></div>
                </div>
                <div class="stage-detail" id="scene-stage-detail">等待开始...</div>
            </div>
            
            <!-- 加载项列表 -->
            <div id="project-loading-items-list" class="loading-items-list" style="display: none;"></div>
        </div>
    </div>
    
    <!-- 场景加载界面（单阶段：仅场景）-->
    <div id="scene-loading-overlay" class="loading-overlay" style="display: none;">
        <div class="loading-container">
            <!-- 加载动画 -->
            <div class="loading-spinner"></div>
            
            <!-- 标题 -->
            <div class="loading-title">加载场景中</div>
            <div class="loading-subtitle">正在准备您的工作环境...</div>
            
            <!-- 单阶段: 加载场景 -->
            <div class="loading-stage single-stage">
                <div class="stage-header">
                    <span class="stage-icon" id="single-scene-icon">🔄</span>
                    <span class="stage-title">加载场景</span>
                    <span class="stage-percent" id="single-scene-percent">0%</span>
                </div>
                <div class="stage-progress-container">
                    <div id="single-scene-bar" class="stage-progress-bar"></div>
                </div>
                <div class="stage-detail" id="single-scene-detail">初始化...</div>
            </div>
            
            <!-- 加载项列表 -->
            <div id="scene-loading-items-list" class="loading-items-list" style="display: none;"></div>
        </div>
    </div>
    
    <!-- 顶部控制栏 -->
    <div id="top-controls" class="control-bar">
        <!-- 项目管理按钮 -->
        <button id="projectBtn" class="toolbar-btn">
            📁 <span id="current-project-name">加载中...</span>
        </button>
        
        <!-- 场景管理按钮 -->
        <button id="sceneManageBtn" class="toolbar-btn" title="点击管理场景">
            🎬 <span id="current-scene-name">加载中...</span>
        </button>
        
        <!-- 分隔线 -->
        <div class="toolbar-divider"></div>
        
        <!-- 比例尺切换按钮 -->
        <button id="scaleGridBtn" class="toolbar-btn toolbar-btn-scale" onclick="toggleScaleGrid()" title="切换比例尺显示">
            📏
        </button>
        
        <!-- 参考地面切换按钮 -->
        <button id="groundPlaneBtn" class="toolbar-btn toolbar-btn-ground active" onclick="toggleGroundPlane()" title="切换参考地面显示">
            🟩
        </button>
        
        <!-- 分隔线 -->
        <div class="toolbar-divider"></div>
        
        <!-- Transform 模式切换按钮组 -->
        <div class="toolbar-btn-group">
            <button id="transformTranslateBtn" class="toolbar-btn active" onclick="setTransformMode('translate')" title="平移模式（快捷键: W）">
                ↔️ 平移
            </button>
            <button id="transformRotateBtn" class="toolbar-btn" onclick="setTransformMode('rotate')" title="旋转模式（快捷键: E）">
                🔄 旋转
            </button>
            <button id="transformScaleBtn" class="toolbar-btn" onclick="setTransformMode('scale')" title="缩放模式（快捷键: R）">
                📏 缩放
            </button>
        </div>
        
        <!-- 分隔线 -->
        <div class="toolbar-divider"></div>
        
        <button id="settingsBtn" class="toolbar-btn">
            ⚙️ 设置
        </button>
    </div>

    <!-- 左侧竖向Tab栏 - 始终可见 -->
    <div id="left-tabs-bar" class="left-tabs-bar">
        <button class="left-vertical-tab-btn active" data-tab="scene-tree" title="层级树">
            <span class="tab-icon">🌲</span>
            <span class="tab-label">层级树</span>
        </button>
        <button class="left-vertical-tab-btn" data-tab="environment" title="环境">
            <span class="tab-icon">🌍</span>
            <span class="tab-label">环境</span>
        </button>
    </div>
    
    <!-- 左侧面板内容 - 可隐藏 -->
    <div id="left-panel-wrapper" class="left-panel-wrapper">
        <!-- 左侧面板容器 -->
        <div id="scene-panel" class="side-panel left-panel">
            <!-- 层级树Tab内容 -->
            <div id="scene-tree-tab" class="left-tab-content active">
                <!-- 层级树标题 -->
                <div class="panel-header">
                    <!-- 多选数量显示 -->
                    <span id="multi-select-count" class="panel-multi-select-count" style="display: none;">
                        已选中 <strong id="selected-count">0</strong> 个
                    </span>
                    <div class="panel-header-actions">
                        <button class="icon-btn edit-only" onclick="addEmptyNode()" title="添加空节点">➕</button>
                        <button class="icon-btn edit-only" onclick="onCameraTitleButtonClick()" title="相机管理">🎥</button>
                        <button class="icon-btn" onclick="expandAllNodes()" title="展开下一级">📂</button>
                        <button class="icon-btn" onclick="collapseAllNodes()" title="折叠全部">📁</button>
                    </div>
                </div>
                
                <!-- 搜索框 -->
                <div class="tree-search-container">
                    <input type="text" id="tree-search-input" class="tree-search-input" placeholder="搜索节点..." />
                    <button class="tree-search-clear" id="tree-search-clear" title="清除搜索" style="display: none;">✕</button>
                </div>
                
                <!-- 层级树内容 -->
                <div class="panel-body">
                    <div class="tree-container" id="scene-tree-container">
                        <div class="tree-loading">加载中...</div>
                    </div>
                </div>
            </div>
            
            <!-- 环境Tab内容 -->
            <div id="environment-tab" class="left-tab-content">
                <!-- 环境标题 -->
                <div class="panel-header">
                    <span class="panel-title">环境设置</span>
                </div>
                
                <!-- 环境设置内容 -->
                <div class="panel-body">
                    <div class="environment-container">
                        <!-- 环境光 -->
                        <div class="env-section">
                            <div class="env-section-header" onclick="toggleEnvSection('light')">
                                <span class="env-icon">💡</span>
                                <span class="env-title">环境光</span>
                            </div>
                            <div class="env-section-body" id="env-section-light">
                                <div class="env-item">
                                    <label>启用环境光</label>
                                    <input type="checkbox" class="env-checkbox" id="env-ambient-enabled" checked onchange="onAmbientLightEnabledChange()" />
                                </div>
                                <div class="env-item">
                                    <label>光照强度</label>
                                    <div class="env-slider-container">
                                        <input type="range" class="env-slider" id="env-ambient-intensity" min="0" max="2" step="0.1" value="0.5" oninput="onAmbientIntensityChange()" />
                                        <span class="env-value" id="env-ambient-intensity-value">0.5</span>
                                    </div>
                                </div>
                                <div class="env-item">
                                    <label>光照颜色</label>
                                    <input type="color" class="env-color" id="env-ambient-color" value="#ffffff" onchange="onAmbientColorChange()" />
                                </div>
                            </div>
                        </div>
                        
                        <!-- 操作按钮 -->
                        <div class="env-actions">
                            <button class="env-btn env-btn-primary" onclick="saveEnvironmentSettings()">💾 保存配置</button>
                            <button class="env-btn env-btn-secondary" onclick="resetEnvironmentSettings()">🔄 重置</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


    <!-- Mesh模式面板 -->
    <div id="mesh-structure-panel" class="side-panel left-panel mesh-panel">
        <!-- 面板标题 -->
        <div class="panel-header">
            <div class="panel-title">
                <span class="panel-icon">🔷</span>
                <span id="mesh-panel-title">Mesh模式</span>
            </div>
            <div class="panel-header-actions">
                <button class="icon-btn" id="resetMeshTransformBtn" onclick="resetMeshTransform()" title="重置Mesh变换">🔄</button>
                <button class="icon-btn" id="toggleWireframeBtn" onclick="toggleMeshWireframe()" title="显示/隐藏网格线">🔲</button>
                <button class="icon-btn" onclick="expandAllMeshNodes()" title="展开下一级">📂</button>
                <button class="icon-btn" onclick="collapseAllMeshNodes()" title="折叠全部">📁</button>
                <button class="panel-close-btn" onclick="closeMeshStructurePanel()" title="关闭">✕</button>
            </div>
        </div>
        
        <!-- Mesh搜索框 -->
        <div class="mesh-search-container">
            <input type="text" id="mesh-search-input" class="mesh-search-input" placeholder="搜索全部Mesh..." />
            <button class="mesh-search-clear" id="mesh-search-clear" title="清除搜索" style="display: none;">✕</button>
        </div>
        
        <!-- 面板内容 -->
        <div class="panel-body">
            <div class="mesh-tree-container" id="mesh-tree-container">
                <div class="mesh-empty">
                    <div class="mesh-empty-icon">🔷</div>
                    <div>请选择包含模型的节点</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 模型管理弹窗 -->
    <div id="model-library-manage-modal" class="modal">
        <div class="modal-content modal-large">
            <div class="modal-header">
                <h3>
                    <span>🎨 模型管理</span>
                    <span class="modal-count" id="manage-model-count">共 0 个模型</span>
                </h3>
                <div class="modal-header-actions">
                    <button class="action-btn" onclick="startTwoStageUpload()">📤 上传模型</button>
                    <button class="action-btn" onclick="startNodeGroupUpload()">📤 上传节点模型组</button>
                    <button class="close-btn" onclick="closeModelLibraryManage()">✕</button>
                </div>
            </div>
            
            <!-- Tab切换按钮 -->
            <div class="model-manage-tabs">
                <button class="tab-btn active" data-tab="model-manage">📦 模型库</button>
                <button class="tab-btn" data-tab="node-manage">🎯 节点库</button>
            </div>
            
            <div class="modal-body">
                <!-- 模型库管理Tab -->
                <div class="manage-tab-panel active" id="model-manage-tab">
                    <div class="manage-list" id="model-manage-list">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
                
                <!-- 节点库管理Tab -->
                <div class="manage-tab-panel" id="node-manage-tab">
                    <div class="manage-list" id="node-manage-list">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
                
                <!-- 上传模型对话框（隐藏的文件输入，支持多选） -->
                <!-- 支持拖拽到场景: GLTF/GLB, FBX | 仅存储: OBJ, STL -->
                <input type="file" id="model-upload-input" accept=".glb,.gltf,.obj,.fbx,.stl" multiple style="display: none;" />
            </div>
        </div>
    </div>

    <!-- 批量上传队列弹窗 -->
    <div id="upload-queue-modal" class="modal">
        <div class="modal-content upload-queue-content">
            <div class="modal-header">
                <h3>📤 批量上传模型</h3>
                <button class="close-btn" onclick="closeUploadQueue()">✕</button>
            </div>
            <div class="modal-body">
                <!-- 上传队列列表 -->
                <div class="upload-queue-section">
                    <div class="queue-header">
                        <span class="queue-title">上传队列 (<span id="queue-count">0</span>)</span>
                        <!-- 清空按钮已移除 -->
                    </div>
                    <!-- 上传完成提示 -->
                    <div id="upload-complete-message" class="upload-complete-message" style="display: none;">
                        <div class="complete-icon">🎉</div>
                        <div class="complete-text" id="upload-complete-text">上传完成！</div>
                    </div>
                    <div class="upload-queue-list" id="upload-queue-list">
                        <div class="queue-empty">暂无文件，请选择文件添加到队列</div>
                    </div>
                </div>
                
                <!-- 当前上传进度 -->
                <div class="current-upload-progress" id="current-upload-progress" style="display: none;">
                    <div class="progress-header">当前上传</div>
                    <div class="upload-file-info">
                        <div class="upload-icon" id="current-upload-icon">📦</div>
                        <div class="upload-file-details">
                            <div class="upload-file-name" id="current-upload-name">--</div>
                            <div class="upload-file-size" id="current-upload-size">--</div>
                        </div>
                    </div>
                    
                    <div class="upload-progress-bar">
                        <div class="upload-progress-fill" id="current-upload-fill"></div>
                    </div>
                    
                    <div class="upload-progress-text">
                        <span id="current-upload-status">准备中...</span>
                        <span id="current-upload-percent">0%</span>
                    </div>
                </div>
                
                <!-- 操作按钮 -->
                <div class="upload-actions">
                    <button id="add-more-btn" class="action-btn" onclick="addMoreFiles()">➕ 添加文件</button>
                    <button id="start-upload-btn" class="action-btn primary-btn" onclick="startBatchUpload()" disabled>开始上传</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 自定义确认对话框 -->
    <div id="custom-confirm-dialog" class="modal" style="z-index: 10000;">
        <div class="modal-content confirm-dialog-content">
            <div class="modal-header">
                <h3 id="confirm-dialog-title">确认操作</h3>
            </div>
            <div class="modal-body">
                <div class="confirm-dialog-message" id="confirm-dialog-message">
                    确定要执行此操作吗？
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" id="confirm-dialog-cancel">取消</button>
                <button class="btn-primary btn-danger" id="confirm-dialog-confirm">确定</button>
            </div>
        </div>
    </div>

    <!-- 编辑模型信息弹窗 -->
    <div id="edit-model-dialog" class="modal" style="z-index: 10000;">
        <div class="modal-content confirm-dialog-content">
            <div class="modal-header">
                <h3>✏️ 编辑模型信息</h3>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>模型名称</label>
                    <input type="text" id="edit-model-name" class="form-input" placeholder="请输入模型名称">
                </div>
                <div class="form-group">
                    <label>缩放比例</label>
                    <input type="number" id="edit-model-scale" class="form-input" placeholder="0.01" step="0.01" min="0.001" max="100">
                    <small style="color: rgba(255,255,255,0.6); font-size: 12px;">拖拽到场景时的缩放比例（默认0.01）</small>
                </div>
                <div class="form-group">
                    <label>🏷️ 标签</label>
                    <div class="tags-editor">
                        <div class="tags-list" id="edit-model-tags-list">
                            <!-- 已添加的标签显示在这里 -->
                        </div>
                        <div class="tags-input-row">
                            <input type="text" id="edit-model-tags-input" class="tags-input" placeholder="输入标签后按回车添加">
                            <button type="button" id="add-tag-btn" class="add-tag-btn">添加</button>
                        </div>
                    </div>
                    <small style="color: rgba(255,255,255,0.6); font-size: 12px;">输入标签后按回车或点击"添加"按钮</small>
                </div>
                <div class="form-group">
                    <label>模型描述</label>
                    <textarea id="edit-model-description" class="form-textarea" rows="3" placeholder="请输入模型描述（可选）"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" id="edit-model-cancel">取消</button>
                <button class="btn-primary" id="edit-model-confirm">保存</button>
            </div>
        </div>
    </div>

    <!-- 设置面板 -->
    <div id="settings-panel" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>⚙️ 设置</h3>
                <button class="close-btn" onclick="closeSettingsPanel()">✕</button>
            </div>
            <div class="modal-body">
                <div class="settings-list">
                    <!-- 账号信息（仅在启用认证时显示） -->
                    <div class="setting-item auth-only" style="cursor: default;">
                        <div class="setting-icon">👤</div>
                        <div class="setting-info">
                            <div class="setting-title">当前账号</div>
                            <div class="setting-desc"><span id="current-user">加载中...</span></div>
                        </div>
                    </div>
                    
                    <!-- 管理员后台 -->
                    <div class="setting-item" onclick="openAdminPage()">
                        <div class="setting-icon">👨‍💼</div>
                        <div class="setting-info">
                            <div class="setting-title">管理员后台</div>
                            <div class="setting-desc">管理系统配置和用户权限</div>
                        </div>
                        <div class="setting-arrow">›</div>
                    </div>
                    
                    <!-- 退出登录（仅在启用认证时显示） -->
                    <div class="setting-item auth-only" id="logoutBtn" style="cursor: pointer;">
                        <div class="setting-icon">🚪</div>
                        <div class="setting-info">
                            <div class="setting-title">退出登录</div>
                            <div class="setting-desc">退出当前账号</div>
                        </div>
                        <div class="setting-arrow">›</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 项目管理面板背景遮罩 -->
    <div id="project-panel-overlay" style="display: none;"></div>
    
    <!-- 项目管理面板 -->
    <div id="project-panel" style="display: none;">
        <div class="panel-header">
            <h2>📁 项目管理</h2>
            <button id="closeProjectPanel" class="close-btn">✕</button>
        </div>
        <div class="panel-body">
            <!-- 当前项目信息 -->
            <div class="current-project-info">
                <h3>当前项目</h3>
                <div id="currentProjectDisplay" class="project-card current">
                    <div class="project-name">加载中...</div>
                </div>
            </div>
            
            <!-- 项目列表 -->
            <div class="project-list-section">
                <div class="section-header">
                    <h3>所有项目</h3>
                    <button id="createProjectBtn" class="action-btn">➕ 新建项目</button>
                </div>
                <div id="projectList" class="project-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建项目 Modal -->
    <div id="createProjectModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>创建新项目</h3>
                <button class="close-btn" onclick="closeCreateProjectModal()">✕</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="newProjectName">项目名称 *</label>
                    <input type="text" id="newProjectName" placeholder="请输入项目名称" required>
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeCreateProjectModal()">取消</button>
                <button class="btn-primary" onclick="confirmCreateProject()">创建</button>
            </div>
        </div>
    </div>

    <!-- 场景管理面板（带遮罩） -->
    <div id="scene-manage-panel" class="modal">
        <div class="modal-content scene-manage-modal">
            <div class="panel-header">
                <h2>🎬 场景管理</h2>
                <div class="header-actions">
                    <button id="createSceneBtn" class="action-btn">➕ 新建场景</button>
                    <button id="closeSceneManagePanel" class="close-btn">✕</button>
                </div>
            </div>
            <div class="panel-body">
                <div id="sceneList" class="scene-list">
                    <div class="loading">加载中...</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 创建场景 Modal -->
    <div id="createSceneModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>创建新场景</h3>
                <button class="close-btn" onclick="closeCreateSceneModal()">✕</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="newSceneName">场景名称 *</label>
                    <input type="text" id="newSceneName" placeholder="请输入场景名称" required>
                </div>
                <div class="form-group">
                    <label for="newSceneDescription">场景描述</label>
                    <input type="text" id="newSceneDescription" placeholder="请输入场景描述（可选）">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn-secondary" onclick="closeCreateSceneModal()">取消</button>
                <button class="btn-primary" onclick="confirmCreateScene()">创建</button>
            </div>
        </div>
    </div>

    <!-- 屏幕比例尺显示 -->
    <div id="screen-scale-indicator" class="screen-scale-indicator">
        <div class="scale-line"></div>
        <div class="scale-label">10m</div>
    </div>

    <!-- 右侧Tab按钮栏（垂直） -->
    <div id="right-tabs-bar" class="right-tabs-bar">
        <button class="vertical-tab-btn" data-panel="transform" title="属性">
            <span class="tab-icon">🎯</span>
            <span class="tab-label">属性</span>
        </button>
        <button class="vertical-tab-btn" data-panel="camera" title="相机">
            <span class="tab-icon">🎥</span>
            <span class="tab-label">相机</span>
        </button>
        <button class="vertical-tab-btn" data-panel="model-library" title="模型">
            <span class="tab-icon">📦</span>
            <span class="tab-label">模型</span>
        </button>
        <button class="vertical-tab-btn" data-panel="material-editor" title="材质编辑器">
            <span class="tab-icon">🎨</span>
            <span class="tab-label">材质</span>
        </button>
        <button class="vertical-tab-btn" data-panel="texture-library" title="贴图库">
            <span class="tab-icon">🖼️</span>
            <span class="tab-label">贴图</span>
        </button>
    </div>

    <!-- Transform面板 -->
    <!-- 节点属性面板（Inspector） -->
    <div id="transform-panel" class="right-panel inspector-panel" data-panel="transform">
        <!-- 面板头部 -->
        <div class="panel-header">
            <div class="panel-title">
                <span class="panel-icon">🔍</span>
                <input type="text" id="transform-node-name" class="panel-node-name-input" placeholder="未选中节点" readonly />
                <button id="node-rename-btn" class="node-action-btn" title="重命名" style="display: none;">✏️</button>
            </div>
            <button class="panel-close-btn" onclick="closeRightPanel('transform')" title="关闭">✕</button>
        </div>
        
        <!-- 名称编辑提示 -->
        <div id="name-edit-hint" class="name-edit-hint" style="display: none;">
            <span class="hint-text">💡 按 <kbd>Enter</kbd> 保存，<kbd>Esc</kbd> 取消</span>
        </div>
        
        <!-- 面板内容 -->
        <div class="panel-content">
            
            <!-- 属性控件区域 - 默认隐藏 -->
            <div class="panel-content-body" id="transform-controls-area" style="display: none;">
                
                <!-- 节点操作区域 -->
                <div class="inspector-section node-actions-section">
                    <div class="section-content" style="display: block; padding: 10px 12px;">
                        <div class="node-operations">
                            <button id="node-visible-btn-main" class="node-operation-btn" title="显示/隐藏">
                                <span class="btn-icon">👁</span>
                                <span class="btn-label">可见性</span>
                            </button>
                            <button id="node-delete-btn-main" class="node-operation-btn node-operation-danger" title="删除节点">
                                <span class="btn-icon">🗑</span>
                                <span class="btn-label">删除</span>
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Transform 区域 -->
                <div class="inspector-section">
                    <div class="section-header" onclick="toggleInspectorSection('transform')">
                        <span class="section-icon">▼</span>
                        <span class="section-title">🎯 Transform</span>
                    </div>
                    <div class="section-content" id="section-transform">
                        <!-- 位置 -->
                        <div class="property-row">
                            <label class="property-label">Position</label>
                            <div class="property-values xyz-row">
                                <div class="xyz-input">
                                    <span class="axis-label x-axis">X</span>
                                    <input type="number" id="transform-pos-x" step="0.1" />
                                </div>
                                <div class="xyz-input">
                                    <span class="axis-label y-axis">Y</span>
                                    <input type="number" id="transform-pos-y" step="0.1" />
                                </div>
                                <div class="xyz-input">
                                    <span class="axis-label z-axis">Z</span>
                                    <input type="number" id="transform-pos-z" step="0.1" />
                                </div>
                            </div>
                        </div>
                        
                        <!-- 旋转 -->
                        <div class="property-row">
                            <label class="property-label">Rotation</label>
                            <div class="property-values xyz-row">
                                <div class="xyz-input">
                                    <span class="axis-label x-axis">X</span>
                                    <input type="number" id="transform-rot-x" step="1" />
                                </div>
                                <div class="xyz-input">
                                    <span class="axis-label y-axis">Y</span>
                                    <input type="number" id="transform-rot-y" step="1" />
                                </div>
                                <div class="xyz-input">
                                    <span class="axis-label z-axis">Z</span>
                                    <input type="number" id="transform-rot-z" step="1" />
                                </div>
                            </div>
                        </div>
                        
                        <!-- 缩放 -->
                        <div class="property-row">
                            <label class="property-label">Scale</label>
                            <div class="property-values xyz-row">
                                <div class="xyz-input">
                                    <span class="axis-label x-axis">X</span>
                                    <input type="number" id="transform-scale-x" step="0.1" min="0.001" />
                                </div>
                                <div class="xyz-input">
                                    <span class="axis-label y-axis">Y</span>
                                    <input type="number" id="transform-scale-y" step="0.1" min="0.001" />
                                </div>
                                <div class="xyz-input">
                                    <span class="axis-label z-axis">Z</span>
                                    <input type="number" id="transform-scale-z" step="0.1" min="0.001" />
                                </div>
                            </div>
                        </div>
                        
                        <!-- 重置按钮 -->
                        <div class="property-actions">
                            <button class="property-btn" onclick="resetTransform()">🔄 重置</button>
                        </div>
                    </div>
                </div>
                
                <!-- 组件容器 - 动态显示节点已有的组件 -->
                <div id="components-container">
                    <!-- 组件将在这里动态生成 -->
                </div>
                
                <!-- 添加组件按钮 -->
                <div class="add-component-section">
                    <button class="add-component-btn" onclick="toggleComponentMenu()">
                        ➕ 添加组件
                    </button>
                </div>
                
            </div>
        </div>
        
        <!-- 拖拽调整尺寸手柄 -->
        <div class="resize-handle resize-left"></div>
        <div class="resize-handle resize-bottom"></div>
        <div class="resize-handle resize-corner"></div>
    </div>

    <!-- 相机面板 -->
    <div id="camera-panel" class="right-panel" data-panel="camera">
        <!-- 面板头部 -->
        <div class="panel-header">
            <div class="panel-title">
                <span class="panel-icon">🎥</span>
                <span class="panel-title-text">相机设置</span>
            </div>
            <button class="panel-close-btn" onclick="closeRightPanel('camera')" title="关闭">✕</button>
        </div>
        
        <!-- 面板内容 -->
        <div class="panel-content">
            <div class="panel-body">
                <!-- 提示信息 -->
                <div id="camera-select-hint" class="panel-info" style="display: none;">
                    请选择一个相机节点
                </div>

                <div id="camera-settings-content">
                    <!-- Transform 区域 -->
                    <div class="inspector-section">
                        <div class="section-header" onclick="toggleInspectorSection('camera-transform')">
                            <span class="section-icon">▼</span>
                            <span class="section-title">🎯 Transform</span>
                        </div>
                        <div class="section-content" id="section-camera-transform">
                            <!-- 位置 -->
                            <div class="property-row">
                                <label class="property-label">Position</label>
                                <div class="property-values xyz-row">
                                    <div class="xyz-input">
                                        <span class="axis-label x-axis">X</span>
                                        <input type="number" id="camera-pos-x" step="0.1" />
                                    </div>
                                    <div class="xyz-input">
                                        <span class="axis-label y-axis">Y</span>
                                        <input type="number" id="camera-pos-y" step="0.1" />
                                    </div>
                                    <div class="xyz-input">
                                        <span class="axis-label z-axis">Z</span>
                                        <input type="number" id="camera-pos-z" step="0.1" />
                                    </div>
                                </div>
                            </div>
                            
                            <!-- 旋转 -->
                            <div class="property-row">
                                <label class="property-label">Rotation</label>
                                <div class="property-values xyz-row">
                                    <div class="xyz-input">
                                        <span class="axis-label x-axis">X</span>
                                        <input type="number" id="camera-rot-x" step="1" />
                                    </div>
                                    <div class="xyz-input">
                                        <span class="axis-label y-axis">Y</span>
                                        <input type="number" id="camera-rot-y" step="1" />
                                    </div>
                                    <div class="xyz-input">
                                        <span class="axis-label z-axis">Z</span>
                                        <input type="number" id="camera-rot-z" step="1" />
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 相机参数区域 -->
                    <div class="inspector-section">
                        <div class="section-header" onclick="toggleInspectorSection('camera-params')">
                            <span class="section-icon">▼</span>
                            <span class="section-title">📷 相机参数</span>
                        </div>
                        <div class="section-content" id="section-camera-params">
                            <div class="property-row">
                                <label class="property-label">类型</label>
                                <div class="property-value">
                                    <select id="camera-type" class="form-select" disabled>
                                        <option value="PerspectiveCamera">透视相机</option>
                                    </select>
                                </div>
                            </div>
                            <div class="property-row">
                                <label class="property-label">视场角 (FOV)</label>
                                <div class="property-value">
                                    <input type="number" id="camera-fov" class="form-input" min="1" max="179" step="1">
                                </div>
                            </div>
                            <div class="property-row">
                                <label class="property-label">近裁剪面 (Near)</label>
                                <div class="property-value">
                                    <input type="number" id="camera-near" class="form-input" min="0.001" step="0.1">
                                </div>
                            </div>
                            <div class="property-row">
                                <label class="property-label">远裁剪面 (Far)</label>
                                <div class="property-value">
                                    <input type="number" id="camera-far" class="form-input" min="1" step="10">
                                </div>
                            </div>
                            
                            <!-- 相机分辨率设置 -->
                            <div class="property-row">
                                <label class="property-label">分辨率</label>
                                <div class="property-value">
                                    <select id="camera-resolution" class="form-select">
                                        <option value="window">跟随窗口</option>
                                        <option value="1920x1080">1920 x 1080 (16:9)</option>
                                        <option value="1280x720">1280 x 720 (16:9)</option>
                                        <option value="1080x1920">1080 x 1920 (9:16)</option>
                                        <option value="720x1280">720 x 1280 (9:16)</option>
                                        <option value="custom">自定义</option>
                                    </select>
                                </div>
                            </div>
                            <div class="property-row" id="camera-custom-res-row" style="display: none;">
                                <div class="property-values xyz-row">
                                    <div class="xyz-input">
                                        <span class="axis-label">W</span>
                                        <input type="number" id="camera-res-w" placeholder="宽" value="1920" />
                                    </div>
                                    <div class="xyz-input">
                                        <span class="axis-label">H</span>
                                        <input type="number" id="camera-res-h" placeholder="高" value="1080" />
                                    </div>
                                </div>
                            </div>

                            <div class="property-actions">
                                <button class="property-btn" onclick="resetCameraParams()">🔄 重置参数</button>
                                <button class="property-btn property-btn-primary" id="toggle-camera-view-btn" onclick="toggleCameraView()">👁️ 进入相机视角</button>
                                <button class="property-btn property-btn-primary" onclick="setAsMainCamera()">同步视角到相机</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 拖拽调整尺寸手柄 -->
        <div class="resize-handle resize-left"></div>
        <div class="resize-handle resize-bottom"></div>
        <div class="resize-handle resize-corner"></div>
    </div>

    <!-- 模型库面板 -->
    <div id="model-library-panel-content" class="right-panel" data-panel="model-library">
        <!-- 面板头部 -->
        <div class="panel-header">
            <div class="panel-title">
                <span class="panel-icon">📦</span>
                <span class="panel-title-text">模型</span>
            </div>
            <div class="panel-header-actions">
                <button id="download-all-models-btn" class="header-download-btn" onclick="downloadAllModels()" title="下载所有未下载的模型到缓存">📥</button>
                <button class="manage-btn" onclick="openModelLibraryManage()" title="管理模型库">⚙️</button>
                <button class="panel-close-btn" onclick="closeRightPanel('model-library')" title="关闭">✕</button>
            </div>
        </div>
        
        <!-- Tab切换按钮 -->
        <div class="model-library-tabs">
            <button class="tab-btn active" data-tab="model-library">📦 模型库</button>
            <button class="tab-btn" data-tab="node-library">🎯 节点库</button>
        </div>
        
        <!-- 面板内容 -->
        <div class="panel-content">
            <div class="panel-body">
                <!-- 模型库Tab -->
                <div id="model-library-tab" class="tab-panel active">
                    <!-- 搜索和筛选区域 -->
                    <div class="model-filter-section">
                        <div class="model-search-box">
                            <input type="text" id="model-search-input" placeholder="搜索模型名称..." />
                            <button id="model-search-clear" class="search-clear-btn" title="清除搜索">✕</button>
                        </div>
                        <div class="model-tags-filter">
                            <div class="tags-filter-header">
                                <span class="tags-filter-title">🏷️ 标签筛选</span>
                                <button id="clear-tag-filter" class="clear-filter-btn" title="清除筛选">清除</button>
                            </div>
                            <div id="tags-filter-list" class="tags-filter-list">
                                <!-- 标签列表动态生成 -->
                            </div>
                        </div>
                    </div>
                    <div class="resource-list" id="model-list"></div>
                    <div class="panel-info">拖拽已下载的模型到场景</div>
                </div>
                
                <!-- 节点库Tab -->
                <div id="node-library-tab" class="tab-panel">
                    <!-- 搜索和筛选区域 -->
                    <div class="model-filter-section">
                        <div class="model-search-box">
                            <input type="text" id="node-search-input" placeholder="搜索节点模型..." />
                            <button id="node-search-clear" class="search-clear-btn" title="清除搜索">✕</button>
                        </div>
                        <div class="model-tags-filter">
                            <div class="tags-filter-header">
                                <span class="tags-filter-title">🏷️ 标签筛选</span>
                                <button id="clear-node-tag-filter" class="clear-filter-btn" title="清除筛选">清除</button>
                            </div>
                            <div id="node-tags-filter-list" class="tags-filter-list">
                                <!-- 标签列表动态生成 -->
                            </div>
                        </div>
                    </div>
                    <div class="resource-list" id="node-list"></div>
                    <div class="panel-info">拖拽已下载的节点模型到场景</div>
                </div>
            </div>
        </div>
        
        <!-- 拖拽调整尺寸手柄 -->
        <div class="resize-handle resize-left"></div>
        <div class="resize-handle resize-bottom"></div>
        <div class="resize-handle resize-corner"></div>
    </div>

    <!-- 材质编辑器面板 -->
    <div id="material-editor-panel" class="right-panel" data-panel="material-editor">
        <!-- 面板头部 -->
        <div class="panel-header">
            <div class="panel-title">
                <span class="panel-icon">🎨</span>
                <span class="panel-title-text" id="material-editor-title">材质编辑器</span>
            </div>
            <div class="panel-header-actions">
                <button class="btn-new-material-header" id="btn-new-material" title="新建材质">
                    <span>＋</span>
                    <span>新建材质</span>
                </button>
                <button class="panel-close-btn" onclick="closeRightPanel('material-editor')" title="关闭">✕</button>
            </div>
        </div>
        
        <!-- 面板内容 -->
        <div class="panel-content">
            <div class="panel-body" id="material-editor-body">
                <div class="material-editor-info">请选择模型并点击"编辑材质"</div>
            </div>
        </div>
        
        <!-- 拖拽调整尺寸手柄 -->
        <div class="resize-handle resize-left"></div>
        <div class="resize-handle resize-bottom"></div>
        <div class="resize-handle resize-corner"></div>
    </div>

    <!-- 贴图库面板 -->
    <div id="texture-library-panel" class="right-panel" data-panel="texture-library">
        <!-- 面板头部 -->
        <div class="panel-header">
            <div class="panel-title">
                <span class="panel-icon">🖼️</span>
                <span class="panel-title-text">贴图库</span>
            </div>
            <div class="panel-header-actions">
                <button class="header-action-btn" id="upload-texture-btn" title="上传贴图">📤</button>
                <button class="panel-close-btn" onclick="closeRightPanel('texture-library')" title="关闭">✕</button>
            </div>
        </div>
        
        <!-- 面板内容 -->
        <div class="panel-content">
            <div class="panel-body" id="texture-library-body">
                <!-- 搜索框 -->
                <div class="texture-library-search">
                    <input type="text" id="texture-library-search-input" class="texture-search-input" placeholder="搜索贴图..." />
                    <button class="texture-search-clear" id="texture-library-search-clear" title="清除搜索" style="display: none;">✕</button>
                </div>
                
                <!-- 贴图统计信息 -->
                <div class="texture-library-stats">
                    <div class="stats-item">
                        <span class="stats-label">总贴图数</span>
                        <span class="stats-value" id="texture-total-count">0</span>
                    </div>
                    <div class="stats-item">
                        <span class="stats-label">已使用</span>
                        <span class="stats-value" id="texture-used-count">0</span>
                    </div>
                    <div class="stats-item">
                        <span class="stats-label">未使用</span>
                        <span class="stats-value" id="texture-unused-count">0</span>
                    </div>
                </div>
                
                <!-- 贴图列表 -->
                <div class="texture-library-list" id="texture-library-list">
                    <div class="empty-state">
                        <div class="empty-icon">🖼️</div>
                        <div class="empty-text">暂无贴图</div>
                        <div class="empty-hint">上传贴图后将在此显示</div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 拖拽调整尺寸手柄 -->
        <div class="resize-handle resize-left"></div>
        <div class="resize-handle resize-bottom"></div>
        <div class="resize-handle resize-corner"></div>
    </div>

    <!-- 左侧Tab切换功能 -->
    <script>
        // 初始化左侧Tab切换（独立显隐控制）
        document.addEventListener('DOMContentLoaded', function() {
            const leftTabButtons = document.querySelectorAll('.left-vertical-tab-btn');
            const panelWrapper = document.getElementById('left-panel-wrapper');
            const meshPanel = document.getElementById('mesh-structure-panel');
            
            leftTabButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const targetTab = this.getAttribute('data-tab');
                    toggleLeftTab(targetTab, this);
                });
            });
            
            // 初始化Mesh面板状态（检查左侧面板是否隐藏）
            if (meshPanel && panelWrapper) {
                if (panelWrapper.classList.contains('hidden')) {
                    meshPanel.classList.add('left-panel-hidden');
                } else {
                    meshPanel.classList.remove('left-panel-hidden');
                }
            }
        });
        
        /**
         * 切换左侧Tab的显示/隐藏（互斥显示，但按钮可控制显隐）
         * @param {string} tabName - tab名称 (scene-tree, environment, skybox)
         * @param {HTMLElement} button - 点击的按钮元素
         */
        function toggleLeftTab(tabName, button) {
            const targetContent = document.getElementById(tabName + '-tab');
            const panelWrapper = document.getElementById('left-panel-wrapper');
            const allButtons = document.querySelectorAll('.left-vertical-tab-btn');
            const allContents = document.querySelectorAll('.left-tab-content');
            const meshPanel = document.getElementById('mesh-structure-panel');
            
            if (!targetContent || !panelWrapper) {
                console.error('❌ 缺少必要元素，退出');
                return;
            }
            
            // 判断当前tab是否已激活
            const isActive = button.classList.contains('active');
            
            if (isActive) {
                // 如果当前tab已激活，点击则隐藏
                button.classList.remove('active');
                targetContent.classList.remove('active');
                panelWrapper.classList.add('hidden');
                
                // 左侧面板隐藏时，通知Mesh面板调整位置
                if (meshPanel) {
                    const meshIsActive = meshPanel.classList.contains('active');
                    if (meshIsActive) {
                        meshPanel.classList.add('left-panel-hidden');
                    }
                }
            } else {
                // 如果当前tab未激活，则先隐藏所有其他tab（互斥）
                allButtons.forEach(btn => btn.classList.remove('active'));
                allContents.forEach(content => content.classList.remove('active'));
                
                // 然后显示当前tab
                button.classList.add('active');
                targetContent.classList.add('active');
                panelWrapper.classList.remove('hidden');
                
                // 左侧面板显示时，通知Mesh面板调整位置
                if (meshPanel) {
                    const meshIsActive = meshPanel.classList.contains('active');
                    if (meshIsActive) {
                        meshPanel.classList.remove('left-panel-hidden');
                    }
                }
            }
        }
        
        /**
         * 切换环境设置区域的折叠/展开状态
         * @param {string} sectionName - 区域名称
         */
        function toggleEnvSection(sectionName) {
            const sectionBody = document.getElementById('env-section-' + sectionName);
            if (!sectionBody) return;
            
            if (sectionBody.style.display === 'none' || !sectionBody.style.display) {
                sectionBody.style.display = 'flex';
            } else {
                sectionBody.style.display = 'none';
            }
        }
        
        
        /**
         * 环境光启用状态变化
         */
        function onAmbientLightEnabledChange() {
            const enabled = document.getElementById('env-ambient-enabled').checked;
            if (window.environmentManager) {
                window.environmentManager.updateAmbientLight({ enabled });
            }
        }
        
        /**
         * 环境光强度变化
         */
        function onAmbientIntensityChange() {
            const intensity = parseFloat(document.getElementById('env-ambient-intensity').value);
            document.getElementById('env-ambient-intensity-value').textContent = intensity.toFixed(1);
            
            if (window.environmentManager) {
                window.environmentManager.updateAmbientLight({ intensity });
            }
        }
        
        /**
         * 环境光颜色变化
         */
        function onAmbientColorChange() {
            const color = document.getElementById('env-ambient-color').value;
            if (window.environmentManager) {
                window.environmentManager.updateAmbientLight({ color });
            }
        }
        
        /**
         * 保存环境设置
         */
        async function saveEnvironmentSettings() {
            if (!window.environmentManager) {
                alert('环境管理器未初始化');
                return;
            }
            
            const success = await window.environmentManager.saveConfig();
            if (success) {
                alert('✅ 环境配置已保存');
            } else {
                alert('❌ 保存失败，请查看控制台');
            }
        }
        
        /**
         * 重置环境设置为默认值
         */
        async function resetEnvironmentSettings() {
            if (!confirm('确定要重置所有环境设置为默认值吗？')) {
                return;
            }
            
            // 重置环境光控件为默认值
            document.getElementById('env-ambient-enabled').checked = true;
            document.getElementById('env-ambient-intensity').value = '0.5';
            document.getElementById('env-ambient-intensity-value').textContent = '0.5';
            document.getElementById('env-ambient-color').value = '#ffffff';
            
            // 应用到环境管理器
            if (window.environmentManager) {
                window.environmentManager.updateAmbientLight({
                    enabled: true,
                    intensity: 0.5,
                    color: '#ffffff'
                });
            }
            
            alert('环境设置已重置为默认值');
        }
        
        /**
         * 更新环境光UI显示
         */
        function updateEnvironmentUI() {
            
            // 更新环境光UI
            if (!window.environmentManager) return;
            
            const config = window.environmentManager.getConfig();
            
            if (config.ambientLight) {
                document.getElementById('env-ambient-enabled').checked = config.ambientLight.enabled;
                document.getElementById('env-ambient-intensity').value = config.ambientLight.intensity;
                document.getElementById('env-ambient-intensity-value').textContent = config.ambientLight.intensity.toFixed(1);
                document.getElementById('env-ambient-color').value = config.ambientLight.color;
            }
        }
    </script>
    
    <!-- Inspector 面板折叠/展开功能 -->
    <script>
        /**
         * 切换 Inspector 区域的折叠/展开状态
         * @param {Event|string} eventOrSectionName - 事件对象或区域名称
         * @param {string} sectionName - 区域名称（transform, model, light, particle, ui3d）
         */
        function toggleInspectorSection(eventOrSectionName, sectionName) {
            // 兼容两种调用方式：
            // 1. toggleInspectorSection('transform') - 只传入 sectionName
            // 2. toggleInspectorSection(event, 'component-model') - 传入 event 和 sectionName
            let actualSectionName;
            if (typeof eventOrSectionName === 'string') {
                actualSectionName = eventOrSectionName;
            } else {
                actualSectionName = sectionName;
            }
            
            const sectionContent = document.getElementById(`section-${actualSectionName}`);
            if (!sectionContent) {
                console.error(`Section content not found for: section-${actualSectionName}`);
                return;
            }
            
            const sectionHeader = sectionContent.previousElementSibling;
            if (!sectionHeader) {
                console.error(`Section header not found for: section-${actualSectionName}`);
                return;
            }
            
            const sectionIcon = sectionHeader.querySelector('.section-icon');
            if (!sectionIcon) {
                console.error(`Section icon not found for: section-${actualSectionName}`);
                return;
            }
            
            if (sectionContent.classList.contains('collapsed')) {
                // 展开
                sectionContent.classList.remove('collapsed');
                sectionIcon.classList.remove('collapsed');
                sectionIcon.textContent = '▼';
            } else {
                // 折叠
                sectionContent.classList.add('collapsed');
                sectionIcon.classList.add('collapsed');
                sectionIcon.textContent = '▶';
            }
        }
        
        /**
         * 切换组件菜单的显示/隐藏
         */
        function toggleComponentMenu() {
            const menu = document.getElementById('component-menu');
            const btn = document.querySelector('.add-component-btn');
            
            if (!menu) {
                console.error('Component menu element not found');
                return;
            }
            
            if (!btn) {
                console.error('Add component button not found');
                return;
            }
            
            const isHidden = menu.style.display === 'none' || !menu.style.display || menu.style.display === '';
            
            if (isHidden) {
                // 计算按钮位置
                const rect = btn.getBoundingClientRect();
                
                // 将菜单定位到按钮下方
                menu.style.left = rect.left + 'px';
                menu.style.top = (rect.bottom + 4) + 'px';
                menu.style.width = rect.width + 'px';
                menu.style.display = 'block';
                
                // 点击外部关闭菜单
                setTimeout(() => {
                    document.addEventListener('click', closeComponentMenuOnClickOutside);
                }, 0);
            } else {
                menu.style.display = 'none';
                document.removeEventListener('click', closeComponentMenuOnClickOutside);
            }
        }
        
        /**
         * 点击外部关闭组件菜单
         */
        function closeComponentMenuOnClickOutside(event) {
            const menu = document.getElementById('component-menu');
            const btn = document.querySelector('.add-component-btn');
            
            if (!menu.contains(event.target) && !btn.contains(event.target)) {
                menu.style.display = 'none';
                document.removeEventListener('click', closeComponentMenuOnClickOutside);
            }
        }
        
        /**
         * 添加组件到节点
         * @param {string} componentType - 组件类型（model, light, particle, ui3d）
         */
        function addComponentToNode(componentType) {
            // 关闭菜单
            const menu = document.getElementById('component-menu');
            menu.style.display = 'none';
            document.removeEventListener('click', closeComponentMenuOnClickOutside);
            
            // 调用 transformPanel 的方法
            if (window.transformPanel) {
                window.transformPanel.addComponent(componentType);
            } else {
                console.error('TransformPanel 未初始化');
            }
        }
        
        /**
         * 从节点移除组件
         * @param {string} componentType - 组件类型（model, light, particle, ui3d）
         */
        function removeComponentFromNode(componentType) {
            if (window.transformPanel) {
                window.transformPanel.removeComponent(componentType);
            } else {
                console.error('TransformPanel 未初始化');
            }
        }
    </script>
    
    <!-- 组件菜单（独立于面板，避免被父元素 transform 影响） -->
    <div class="component-menu" id="component-menu" style="display: none;">
        <div class="component-menu-item" onclick="addComponentToNode('light')">
            💡 灯光
        </div>
        <div class="component-menu-item" onclick="addComponentToNode('particle')">
            ✨ 粒子特效
        </div>
        <div class="component-menu-item" onclick="addComponentToNode('ui3d')">
            🖼️ 3D UI
        </div>
    </div>
    
    <!-- 主应用脚本 -->
    <!-- 注意：模型库管理器已从 app.js 中剥离到 model-library/modelLibraryManager.js，并在 app.js 中引入 -->
    <script type="module" src="./scripts/core/app.js"></script>
</body>
</html>